# -*- coding: utf-8 -*-
# owner: shenyi

from src.core import credentials
from src.core import logger

from huaweicloudsdkcore.auth.credentials import GlobalCredentials, BasicCredentials
from huaweicloudsdkiam.v3.region.iam_region import IamRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkiam.v3 import *
from huaweicloudsdkecs.v2 import *

class Iam:
    
    @staticmethod
    def get_project_id(region_id):
        """
        获取项目ID
        Docs： https://console.huaweicloud.com/apiexplorer/#/openapi/IAM/sdk?api=KeystoneListProjects
        @param region_id: 区域ID
        @return: 项目ID
        """
        huawei_creds = credentials().huawei()
        credentials_obj = GlobalCredentials(
            huawei_creds.get("access_key_id"),
            huawei_creds.get("access_key_secret")
        )

        client = IamClient.new_builder() \
            .with_credentials(credentials_obj) \
            .with_region(IamRegion.value_of(region_id)) \
            .build()

        try:
            request = KeystoneListProjectsRequest(name=region_id)
            response = client.keystone_list_projects(request)
            logger.info("projects:{}".format(response.projects))
            
            return response.projects[0].id
        except exceptions.ClientRequestException as e:
            logger.error(f"Failed to get project ID: {e.error_msg}")
            raise


class Client:
    @staticmethod
    def ecs_client(region_id):
        """
        使用AK&SK初始化ECS客户端
        @param region_id: 区域ID
        @return: EcsClient
        """
        huawei_creds = credentials().huawei()
        project_id = Iam.get_project_id(region_id)
        credentials_obj = BasicCredentials(
            huawei_creds.get("access_key_id"),
            huawei_creds.get("access_key_secret"),
            project_id
        )
        client = EcsClient.new_builder() \
            .with_credentials(credentials_obj) \
            .with_region(region_id) \
            .build()
            
        return client